/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.inf.ufg.view.cadastros;

import br.inf.ufg.model.TipoAssentos;
import br.inf.ufg.model.TipoAssentosDAO;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author umarley.faria
 */
public class TelaCadastroTiposAssentos extends javax.swing.JFrame {

    /**
     * Creates new form TelaCadastroLocal
     */
    public TelaCadastroTiposAssentos() {
        initComponents();
       // super(parent, modal);
        this.setLocationRelativeTo(this);
        this.setResizable(false);
        
        iniciarBD();
        //montarListaCidade();
        primeiro();
    
       
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btFirst = new javax.swing.JButton();
        btPrev = new javax.swing.JButton();
        btNext = new javax.swing.JButton();
        btLast = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btNovo = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();
        btEditar = new javax.swing.JButton();
        btDeletar = new javax.swing.JButton();
        btPesquisar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tfCodigo = new javax.swing.JTextField();
        tfDescricao = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro Tipos de Assentos");
        setAlwaysOnTop(true);

        jToolBar1.setRollover(true);

        btFirst.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/resultset_first.png"))); // NOI18N
        btFirst.setToolTipText("Primeiro Registro");
        btFirst.setFocusable(false);
        btFirst.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btFirst.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btFirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFirstActionPerformed(evt);
            }
        });
        jToolBar1.add(btFirst);

        btPrev.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/resultset_previous.png"))); // NOI18N
        btPrev.setToolTipText("Anterior");
        btPrev.setFocusable(false);
        btPrev.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btPrev.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPrevActionPerformed(evt);
            }
        });
        jToolBar1.add(btPrev);

        btNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/resultset_next.png"))); // NOI18N
        btNext.setToolTipText("Próximo");
        btNext.setFocusable(false);
        btNext.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btNext.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNextActionPerformed(evt);
            }
        });
        jToolBar1.add(btNext);

        btLast.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/resultset_last.png"))); // NOI18N
        btLast.setToolTipText("Último Registro");
        btLast.setFocusable(false);
        btLast.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btLast.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btLast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLastActionPerformed(evt);
            }
        });
        jToolBar1.add(btLast);
        jToolBar1.add(jSeparator1);

        btNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/add.png"))); // NOI18N
        btNovo.setToolTipText("Novo");
        btNovo.setFocusable(false);
        btNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });
        jToolBar1.add(btNovo);

        btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/disk.png"))); // NOI18N
        btSalvar.setToolTipText("Salvar");
        btSalvar.setFocusable(false);
        btSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });
        jToolBar1.add(btSalvar);

        btEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/pencil.png"))); // NOI18N
        btEditar.setToolTipText("Editar");
        btEditar.setFocusable(false);
        btEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditarActionPerformed(evt);
            }
        });
        jToolBar1.add(btEditar);

        btDeletar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/delete.png"))); // NOI18N
        btDeletar.setToolTipText("Remover");
        btDeletar.setFocusable(false);
        btDeletar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btDeletar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btDeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeletarActionPerformed(evt);
            }
        });
        jToolBar1.add(btDeletar);

        btPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inf/ufg/view/images/magnifier.png"))); // NOI18N
        btPesquisar.setToolTipText("Procurar");
        btPesquisar.setFocusable(false);
        btPesquisar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btPesquisar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });
        jToolBar1.add(btPesquisar);

        jLabel1.setText("Código:");

        jLabel2.setText("Descrição:");

        tfCodigo.setEditable(false);

        tfDescricao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfDescricaoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(383, 383, 383))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(340, 340, 340))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 37, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        
        //JOptionPane.showMessageDialog(null, "Teste");
        novo();
        
        
        
    }//GEN-LAST:event_btNovoActionPerformed

    private void btFirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFirstActionPerformed
        primeiro();
    }//GEN-LAST:event_btFirstActionPerformed

    private void btPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPrevActionPerformed
        anterior();
    }//GEN-LAST:event_btPrevActionPerformed

    private void btNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNextActionPerformed
        proximo();
    }//GEN-LAST:event_btNextActionPerformed

    private void btLastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLastActionPerformed
       ultimo();
    }//GEN-LAST:event_btLastActionPerformed

    private void tfDescricaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfDescricaoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfDescricaoActionPerformed

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        salvar();
    }//GEN-LAST:event_btSalvarActionPerformed

    private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditarActionPerformed
       editar();
    }//GEN-LAST:event_btEditarActionPerformed

    private void btDeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeletarActionPerformed
        try {
            remover();
        } catch (SQLException ex) {
            Logger.getLogger(TelaCadastroTiposAssentos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btDeletarActionPerformed

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        pesquisar();
    }//GEN-LAST:event_btPesquisarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroTiposAssentos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroTiposAssentos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroTiposAssentos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaCadastroTiposAssentos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaCadastroTiposAssentos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btDeletar;
    private javax.swing.JButton btEditar;
    private javax.swing.JButton btFirst;
    private javax.swing.JButton btLast;
    private javax.swing.JButton btNext;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JButton btPrev;
    private javax.swing.JButton btSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField tfCodigo;
    private javax.swing.JTextField tfDescricao;
    // End of variables declaration//GEN-END:variables

    
    private TipoAssentosDAO assentoDao;
    
    
private void iniciarBD() {
        
        
        try {
             assentoDao = new TipoAssentosDAO();
        } catch ( Exception e ) {
            JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
        }
 }    
    
public void mostrarDados( TipoAssentos assento ) {
    try{
        
            int codigo = assento.getIdTipo();
            String Descricao = assento.getDescricao();
            
            tfCodigo.setText(String.valueOf(codigo) );
            tfDescricao.setText(Descricao);
            
            
            
            
         // System.out.println(Descricao);
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
        }
        
 }


private void novo(){
    tfDescricao.setEditable(true);
    tfCodigo.setText("");
    tfDescricao.setText("");
    
    
}


private void pesquisar(){
    
    
    
    String criterio = JOptionPane.showInputDialog( this, "Digite um critério para pesquisar");
    
    if(! criterio.isEmpty()){
        if(criterio.matches("^\\d+$")){
            int codigo = Integer.parseInt(criterio);

            try{
                TipoAssentos dados = assentoDao.getTipoAssento(codigo);
                          if ( dados != null ) {
                              mostrarDados( dados );                    
                              JOptionPane.showMessageDialog( this, "Registro Encontrado." );
                          } else {
                              JOptionPane.showMessageDialog( this, "Registro Não Encontrado ");
                          }
              }catch(Exception e){
                  JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
              } 

            
        }else{
             try{
                TipoAssentos dados = assentoDao.pesquisarAssento(criterio);  
                          if ( dados != null ) {
                              mostrarDados( dados );                    
                              JOptionPane.showMessageDialog( this, "Registro Encontrado." );
                          } else {
                              JOptionPane.showMessageDialog( this, "Registro Não Encontrado ");
                          }
              }catch(Exception e){
                  JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
              }


        }
    
   
    }
    
   /* */
    
    
    
}

public void primeiro() {
    desabilitaCampos();
        try {
                TipoAssentos assento = assentoDao.primeiro();

                if ( assento != null) {
                    mostrarDados( assento );
                }                    
            
        } catch ( SQLException e ) {
            JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
        }
}
    
    public void anterior() {
        
            desabilitaCampos();
        
          try {
                TipoAssentos assento = assentoDao.anterior();
                 // System.err.println(assento);
                if ( assento != null) {
                    mostrarDados( assento );
                }                    
            
        } catch ( SQLException e ) {
            JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
        }
    }
    
     public void proximo() {
         desabilitaCampos();
          try {
                TipoAssentos assento = assentoDao.proximo();

                if ( assento != null) {
                    mostrarDados( assento );
                }                    
            
        } catch ( SQLException e ) {
            JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
        }
    }
     
      public void ultimo() {
          desabilitaCampos();
          try {
                TipoAssentos assento = assentoDao.ultimo();

                if ( assento != null) {
                    mostrarDados( assento );
                }                    
            
        } catch ( SQLException e ) {
            JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
        }
    }
      
      
      public void salvar(){
          
          TipoAssentos assento = new TipoAssentos();
          
          if(tfDescricao.getText().isEmpty()){
              
               JOptionPane.showMessageDialog( this, "Preencha a Descrição" );
              
          }else{
              
          
                if(tfCodigo.getText().isEmpty()){
                    assento.setDescricao(tfDescricao.getText());
                    try{
                        assentoDao.salvarRegistro(assento);
                        JOptionPane.showMessageDialog( this, "Salvo com Sucesso" );
                        primeiro();
                    }catch(Exception e){
                        JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
                    }
                }else{
                    assento.setIdTipo(Integer.parseInt( tfCodigo.getText() ));
                    assento.setDescricao(tfDescricao.getText());
                    try{
                        assentoDao.atualizarRegistro(assento);
                        JOptionPane.showMessageDialog( this, "Atualizado com Sucesso" );
                    }catch(Exception e){
                        JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
                    }


                }
          }
          
      }
      
      private void editar(){
          
          habilitaCampos();
          
      }
      
      private void desabilitaCampos(){
          tfDescricao.setEditable(false);
      }
      
      private void habilitaCampos(){
          tfDescricao.setEditable(true);
          tfDescricao.setFocusable(rootPaneCheckingEnabled);
      }
      
      
      private void remover() throws SQLException{
          
          
          int resposta = JOptionPane.showConfirmDialog(rootPane, "Deseja Realmente Excluir este registro?", "Pergunta", JOptionPane.CANCEL_OPTION);
          
          if(resposta == JOptionPane.OK_OPTION){
              
              TipoAssentos assento = new TipoAssentos();
              assento.setIdTipo(Integer.parseInt( tfCodigo.getText()));
              
              try{
                  assentoDao.excluirRegistro(assento);
                  primeiro();
              }catch(SQLException e){
                  JOptionPane.showMessageDialog( this, "Erro: " + e.getMessage() );
              }
              
              
          }
          
          
      }


}
